<template>
    <!-- 用户列表 -->
    <div ref="content" class="box">
        <div class="list-title" ref="listTitle">
            <div>
                <span>关键字：</span>
                <el-input v-model="that.form.keywords" placeholder="请输入用户姓名/手机号码" clearable></el-input>
            </div>
            <div>
                <span>用户等级：</span>
                <el-select v-model="that.form.level" placeholder="请选择用户等级" style="width: 100%" clearable>
                    <el-option v-for="item in that.levelList" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </div>

            <div>
                <el-button type="primary" @click="getList(1)">查 询</el-button>
            </div>
        </div>
        <div class="f-ptb-10 dy">
            <el-button type="primary" @click="opration('add')">新增用户</el-button>
            <el-button type="primary" @click="opration('download')">下载模板</el-button>

            <el-upload class="upload-demo" :show-file-list="false" :headers="upload.headers" accept=".xlsx"
                :action="upload.action" :on-success="uploadSuccess" :on-error="uploadError">
                <el-button type="danger">批量上传</el-button>
            </el-upload>
            <el-button type="primary" class="f-ml-10" @click="opration('excel')">导出Excel</el-button>
        </div>

        <div class="table-content" ref="tableContent">
            <el-table :data="that.list" border stripe :height="that.tableHeight"
                :header-cell-style="{ color: '#606266', backgroundColor: '#f8f8f9', 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }">
                <el-table-column type="index" label="序号" width="100" align="center" :index="indexMethod" />
                <el-table-column prop="username" label="用户姓名"></el-table-column>
                <el-table-column prop="avatar" label="头像">
                    <template #default="{ row }">
                        <el-image style="width: 50px; height: 50px" :src="row.avatar" />
                    </template>
                </el-table-column>
                <el-table-column prop="mobile" label="电话">
                    <template #default="{ row }">
                        {{ row.mobile }}
                    </template>
                </el-table-column>
                <el-table-column prop="level" label="等级">
                    <template #default="{ row }">
                        {{ row.level == 1 ? '一级' : row.level == 2 ? '二级' : '三级' }}
                    </template>
                </el-table-column>
                <el-table-column prop="createtime" label="创建时间"></el-table-column>
                <el-table-column prop="updatetime" label="更新时间"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                        <span class="blue pointer" @click="opration('edit', row)">修改</span>

                        <el-popconfirm title="确定要删除该用户吗?" @confirm="opration('del', row)">
                            <template #reference>
                                <span class="blue pointer f-ml-20">删除</span>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="table-footer">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="that.page" :page-sizes="[10, 20, 50, 100, 200, 500, 800]" :page-size="that.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="that.total"></el-pagination>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { successDeal, getStore, removeStore, phoneFormat, locationDownLoad, BlobDownLoad } from '@/utils/utils'
import api from './api/index'
const that = reactive({
    form: {
        level: '',
        keywords: '',
    },
    list: [],
    levelList: [
        {
            value: 1,
            label: '一级代理',
        },
        {
            value: 2,
            label: '二级代理',
        },
        {
            value: 3,
            label: '三级代理',
        },
    ],
    timeList: [],
    total: 0,
    pageSize: 3,
    page: 1,
    tableHeight: 200,
})

const listTitle = ref()
const content = ref()

const $router = useRouter()

onMounted(() => {
    nextTick(() => {
        listenResizeFn()
    })
    getList()
    window.addEventListener('resize', listenResizeFn)
})

const listenResizeFn = () => {
    that.tableHeight = content.value.clientHeight - listTitle.value.clientHeight - 130
}

//每页条数
const handleSizeChange = (val) => {
    that.pageSize = val
    getList()
}
//当前第几页
const handleCurrentChange = (val) => {
    that.page = val
    getList()
}

// 分页索引
const indexMethod = (index) => {
    return (that.page - 1) * that.pageSize + index + 1
}

// 操作
const opration = (name, row) => {
    switch (name) {
        case 'add':
            $router.push('userMangment/add')
            break
        case 'edit':
            $router.push({
                path: 'userMangment/edit',
                query: {
                    id: row.id,
                },
            })
            break
        case 'del':
            api.delUser({ id: row.id }).then((res) => {
                successDeal('操作成功！')
                getList()
            })
            break

        case 'download':
            api.downloadTemplate().then(res => {
                locationDownLoad(res.data.url)
            })

            break
        case 'excel':
            keepJson.value.responseType = "blob",
                api.downloadExcel(keepJson.value).then(res => {

                    let disposition = res.headers['content-disposition']
                    let arr = disposition.split(';')
                    let name = arr[1].split('=')[1]

                    BlobDownLoad(res, decodeURIComponent(name))
                })

            break

        default:
            break
    }
}

// 列表
let keepJson = ref(null)
const getList = (num) => {
    if (num) that.page = 1
    const json = {
        pageSize: that.pageSize,
        page: that.page,
        keywords: that.form.keywords,
        level: that.form.level,
    }
    keepJson.value = JSON.parse(JSON.stringify(json))
    api.userList(json).then((res) => {
        that.list = res.data.list
        that.total = res.data.total
    })
}

// upload上传
const upload = reactive({
    action: '/api/upload',
    headers: { token: getStore('YX_BACK_ZRRDK_USERINFO').token }
})

const uploadSuccess = (data) => {
    api.uploadExcel({ url: data.data.url }).then(res => {
        successDeal(res.msg)

    })
}

const uploadError = (err) => {
    console.log('err', err);

}

onBeforeUnmount(() => {
    // 移除绑定的listenResizeFn事件监听
    window.removeEventListener('resize', listenResizeFn)
})
</script>

<style lang="scss" scoped>
.box {
    width: 100%;
    height: 100%;
}

.list-title {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 5px;
}

.list-title>div {
    display: flex;
    align-items: center;
    padding: 5px 10px;
    width: 25%;
}

.list-title>div>span:nth-child(1) {
    white-space: nowrap;
    width: 70px;
    text-align: center;
}

.box-dailog {
    height: 70vh;
    padding: 20px;
    overflow-y: scroll;
}

.title {
    font-weight: 700;
    color: #303133;
    font-size: 16px;
    padding: 20px 0;
}

.el-descriptions {
    margin-top: 20px !important;
}

.upload-demo {
    display: inline;
    margin-left: 10px;
}
</style>
